<?php
namespace app\admin\controller;
use app\model\Search as SearchModel;
use think\Db;

use app\lib\baidu\Api as baiduApi;


class Search extends Base
{
    public $exception = ['add','search'];
    
    public function __construct(){
        $model = new SearchModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '分类';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $model = $this->model;

        $upload_cn = Db::name('config')->where('key','UPLOAD_IMG_CN')->value('value');
        $fields = [
            'url'=>['name'=>'<img src="'.$upload_cn.'" style="width:100%;" class="upload-btn-img" /> ','type'=>'file','url'=>url('base/uploadSearch')],
            // 'tags'=>['name'=>'分类维度信息（标签）','type'=>'text'],
            // 'tag_logic'=>['name'=>'检索时tag之间的逻辑','type'=>'select1','params'=>['全部满足','满足其一']],


            // 'rn'=>['name'=>'每页显示数量','type'=>'select1','params'=>[5=>'5',10=>'10',20=>'20',50=>'50',100=>'100',200=>'200',500=>'500',1000=>'1000']],
            // 'score'=>['name'=>'相关性分数','type'=>'text','placeholder'=>'（取值范围0-1，越接近1代表相似度越高）'],
        ];
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);

    }

    public function assignSearchs(){
        $model = $this->model;
        $search_params = [
            [
                ['key'=>'name','name'=>'名称','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'name','type'=>'like'],
        ];
        $map = getSearchParam($map_params);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        // 显示筛选
        $this->assignSearchs();

        $list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();
        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function search(){
        $model = $this->model;
        $fields = [
            'must'=>['url'],
            'nomust'=>['tags','tag_logic','rn']
        ];
        $params = paramFilter(request()->param(),$fields);
        if (!empty($params['error_msg'])) {
            return json(['code'=>5000,'msg'=>$params['error_msg']]);
        }
        $params['pn'] = input('pn',0);
        $params['rn'] = input('rn',5);
        if (empty($params['tags'])) {
            unset($params['tag_logic']);
        }

        $result = (new baiduApi())->imageSearch($params);
        if ($result['status'] == 1) {
            $list = $result['list'];

            $score = input('score',0);
            $news = [];
            foreach ($list as $k => $vo) {
                $vo['image'] = Db::name('image')->where('cont_sign',$vo['cont_sign'])->find();
                if (empty($vo['image'])) {
                    continue;
                }
                // if (empty($vo['image']['url'])) {
                //     $vo['image']['url'] = 'javascript:void(0);';
                // }
                $vo['image']['has_url'] = empty($vo['image']['url']) ? 0 : 1;
                if (!empty($score) && $vo['score'] < $score) {
                    $result['has_more'] = false;
                    break;
                }
                $news[] = $vo;
            }

            $pn = $result['has_more'] ? $params['pn'] + 1: -1;
            return json(['code'=>2000,'list'=>$news,'pn'=>$pn]);
        }
    }

    public function add(){
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'must'=>['image'],
                'nomust'=>['description','brief','tags']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            $params = [];
            if (!empty($save_data['brief'])) {
                foreach ($save_data['brief']['name'] as $k => $vo) {
                    $params[$save_data['brief']['name'][$k]] = $save_data['brief']['value'][$k];
                }
            }
            $save_data['brief'] = json_encode($params,JSON_UNESCAPED_UNICODE);

            $image = explode('/',$save_data['image']);
            $image = explode('.',$image[count($image) - 1]);
            $save_data['name'] = $image[0];
            $save_data['extension'] = $image[count($image) - 1];
            $save_data['ctime'] = time();

            $params['url'] = $save_data['image'];
            $result = (new baiduApi())->imageSearch($save_data['image'],json_encode($params,JSON_UNESCAPED_UNICODE),$params['tags']);
            if ($result['status'] == 0) {
                $save_data['status'] = -1;
                $save_data['remark'] = $result['msg'];
            }else{
                $save_data['status'] = 1;
                $save_data['cont_sign'] = $result['cont_sign'];
            }

            if ( $model->save($save_data) ) {
                $this->success("添加成功",url('index'));
            }else{
                $this->error("添加失败");
            }
        }

        $this->assignFields();
        return view('save', [
            
        ]);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'must'=>['name'],
                'nomust'=>['image','description','sort']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
        }

        return parent::updateData($id,$save_data);
    }




   
}
